package com.apcc4m.sfpushbatch.service;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import javax.annotation.PostConstruct;

import org.java_websocket.drafts.Draft_17;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import com.apcc4m.sfpushbatch.common.PushMessage;
import com.apcc4m.sfpushbatch.repository.Notification;

@Service
@PropertySource(value = "classpath:push.properties")
public class PushService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${push.host}")
    private String host;

    @Value("${push.port}")
    private String port;

    @Value("${push.token}")
    private String token;

    private MyWebSocketClient myWebSocketClient;

    private URI serverUri;

    @PostConstruct
    public void init() throws URISyntaxException, InterruptedException {
        serverUri = new URI(String.format("ws://%s:%s/mng?token=%s", host, port, token));
        connect();
    }

    public void connect() throws InterruptedException {
        myWebSocketClient = new MyWebSocketClient(serverUri, new Draft_17());
        myWebSocketClient.connect();
    }

    public void push(Notification notif, List<String> deviceIdList) {
        PushMessage msg = new PushMessage();
        msg.setCmd(PushMessage.MNG_PUSH_SPECIFY);
        JSONArray deviceIdArr = new JSONArray(deviceIdList);
        msg.setToIds(deviceIdArr);
        msg.setFromId("batch server");
        msg.setTitle(notif.getTitle());
        msg.setContent(notif.getContent());
        myWebSocketClient.send(msg);
    }
}
